package cn.peach.hrm.config;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static cn.peach.hrm.constants.MQConstants.*;

/**
 * @Author you
 * @create 2021/11/29 16:24
 */
@Configuration
public class RabbitMQConfig {

    // 定义交换机
    @Bean(EXCHANGE_NAME_TOPIC)
    public Exchange exchangeNameTopic(){
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME_TOPIC).durable(true).build();
    }

    // 创建邮件队列
    @Bean(QUEUE_NAME_EMAIL)
    public Queue emailQueue(){
        return new Queue(QUEUE_NAME_EMAIL,true);
    }

    // 创建短信队列
    @Bean(QUEUE_NAME_SMS)
    public Queue smsQueue(){
        return new Queue(QUEUE_NAME_SMS,true);
    }

    // 创建站内信队列
    @Bean(QUEUE_NAME_MESSAGE)
    public Queue messageQueue(){
        return new Queue(QUEUE_NAME_MESSAGE,true);
    }

    // 绑定邮件队列到交换机
    @Bean
    public Binding emailQueueBinding(){
        return BindingBuilder.bind(emailQueue()).to(exchangeNameTopic()).with("#.email").noargs();
    }
    // 绑定短信队列到交换机
    @Bean
    public Binding smsQueueBinding() {
        return BindingBuilder.bind(smsQueue()).to(exchangeNameTopic()).with("#.sms").noargs();
    }
    // 绑定站内信到教换机
    @Bean
    public Binding messageQueueBinding() {
        return BindingBuilder.bind(messageQueue()).to(exchangeNameTopic()).with("#.sms").noargs();
    }

    // 定义RabbitTemplate 指定JSON转换器
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        // 设置消息回调
        rabbitTemplate.setMandatory(true);
        return rabbitTemplate;
    }

}
